package com.hk.core.authentication.api;

import com.hk.commons.util.SpringContextHolder;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.function.Supplier;

/**
 * @author Kevin
 * @date 2024-03-24 16:11
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class UserPrincipalOperatorFactory {

    public static <T> T getTargetByRole(String role, Class<T> operatorService, Supplier<T> emptySupplier) {
        boolean hasRole = SecurityContextUtils.isAuthenticated() && SecurityContextUtils.hasRole(role);
        return hasRole ? SpringContextHolder.getBeanIfExist(operatorService).orElseGet(emptySupplier) : emptySupplier.get();
    }

    public static <T> T getTargetByRoles(String[] roles, Class<T> operatorService, Supplier<T> emptySupplier) {
        boolean hasRole = SecurityContextUtils.isAuthenticated() && SecurityContextUtils.hasAnyRole(roles);
        return hasRole ? SpringContextHolder.getBeanIfExist(operatorService).orElseGet(emptySupplier) : emptySupplier.get();
    }

    public static <T> T getTargetByPermission(String permission, Class<T> operatorService, Supplier<T> emptySupplier) {
        boolean hasRole = SecurityContextUtils.isAuthenticated() && SecurityContextUtils.getPrincipal().hasPermission(permission);
        return hasRole ? SpringContextHolder.getBeanIfExist(operatorService).orElseGet(emptySupplier) : emptySupplier.get();
    }

    public static <T> T getTargetByPermissions(String[] permissions, Class<T> operatorService, Supplier<T> emptySupplier) {
        boolean hasRole = SecurityContextUtils.isAuthenticated() && SecurityContextUtils.hasAnyPermission(permissions);
        return hasRole ? SpringContextHolder.getBeanIfExist(operatorService).orElseGet(emptySupplier) : emptySupplier.get();
    }
}
